import random
from datetime import datetime,timedelta

from flask import current_app
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand

from info import create_app,db,models
from info.models import User

app = create_app('develop')




manager = Manager(app)
Migrate(app,db)
manager.add_command("db",MigrateCommand)

@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
def create_superuser(username,password):

    admin = User()

    admin.nick_name = username
    admin.mobile = username
    admin.password = password
    admin.is_admin = True

    try:
        db.session.add(admin)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"

    return "创建成功"
@manager.option("-t","--test",dest = "test")
def add_test_user(test):
    user_list = []

    for i in range(0,1000):
        user = User()
        user.mobile = "138%08d"%i
        user.nick_name = "老王%d"%i
        user.password_hash = "pbkdf2:sha256:50000$4UDCul9b$baa59d03b3a2ec37356ebbebc73c7ff9e433674449aaa6cc0448219035848bb6"
        user.last_login = datetime.now() - timedelta(seconds=random.randint(0,3600*24*31))
        user_list.append(user)
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"
    return "创建成功"

if __name__ =="__main__":
    manager.run()